import os
import sys
import importlib
from loguru import logger

_ = os.path.abspath(os.path.dirname(__file__))  # 返回当前文件路径
root_path = os.path.abspath(os.path.join(_, '..'))  # 返回根目录文件夹

sys.path.append(root_path)

from alphalib.backtest.playback import function
from alphalib.config_backtest import output_path
from alphalib.contrib.strategy import z1_playback

if __name__ == '__main__':
    # strategy_name = 'ExampleBias'
    strategy_name = 'StrategyBollCountPunish'
    strategy_module = importlib.import_module(f'strategies.{strategy_name}')
    stg = strategy_module.strategy
    module_name = strategy_module.__name__.split('.')[-1]
    z1_conf = z1_playback.Z1PlaybackConfig(
        compound_name=module_name,
        start_date='2024-01-01',
        end_date='2024-07-20',
        leverage=1,          # 杠杆建议定死在 1
        enable_funding_rate=False,
        auto_reb=True,
    )

    res, curve, account_df, order_df = z1_playback.run_playback(stg, z1_conf)

    save_dir = os.path.join(output_path, module_name)
    if not os.path.exists(save_dir):
        os.makedirs(save_dir)
    equity_res_path = os.path.join(save_dir, '净值持仓数据.csv')
    res.to_csv(equity_res_path, encoding='gbk')
    curve.to_csv(equity_res_path, encoding='gbk', mode='a')
    account_df.to_csv(os.path.join(save_dir, '虚拟账户数据.csv'), encoding='gbk')
    order_df.to_pickle(os.path.join(save_dir, '下单面板数据.pkl'))

    logger.info(f'\n{res.to_markdown()}')
    function.plot_output(curve, res, save_dir, save_html=True)
